package com.wayz.sms.redis.impl;

import com.wayz.sms.redis.RShortMessageId;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 短消息标识实现类
 * 
 * @author wade.liu@wayz.ai
 *
 */
@Repository("rShortMessageId")
public class RShortMessageIdImpl implements RShortMessageId {

	/** Redis模板 */
	@Resource(name = "redisTemplate")
	private RedisTemplate<String, String> redisTemplate = null;

	/** 键值格式 */
	private static final String KEY = "Id:ShortMessage";

	/** 常量相关 */
	/** 放大倍率 */
	private static final long RATIO = 1000000000000L;
	/** 日期模式 */
	private final static String DATE_PATTERN = "yyyyMMdd";

	/**
	 * 递增短消息标识
	 * 
	 * @return 短消息标识
	 */
	public Long increment() {
		// 获取数据
		long date = Long.parseLong(new SimpleDateFormat(DATE_PATTERN).format(new Date()));
		long index = redisTemplate.opsForValue().increment(KEY, 1L);

		// 返回数据
		return date * RATIO + index % RATIO;
	}

	/**
	 * 递增短消息标识
	 * 
	 * @param time 指定时间(毫秒)
	 * @return 短消息标识
	 */
	@Override
	public Long increment(long time) {
		// 获取数据
		long date = Long.parseLong(new SimpleDateFormat(DATE_PATTERN).format(new Date(time)));
		long index = redisTemplate.opsForValue().increment(KEY, 1L);

		// 返回数据
		return date * RATIO + index % RATIO;
	}

}
